package com.scalar.forecast.salesForecastEntry.actionCommands;

import com.scalar.forecast.actionCommands.ActionCommand;
import com.scalar.forecast.salesForecastEntry.forms.SalesForecastEntryForm;
import com.scalar.forecast.salesForecastEntry.dao.SalesForecastEntryDAO;
import com.scalar.forecast.salesForecastEntry.*;
import com.scalar.forecast.commons.SessionKeys;
import com.scalar.forecast.commons.Constants;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.utils.ConfigManager;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Calendar;
import java.text.DecimalFormat;

/**
 * User: Sujan
 * Date: Jul 13, 2005
 * Time: 6:00:42 PM
 */
public class SalesForecastEntryNewCommand extends ActionCommand
{
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception
    {
        SalesForecastEntryForm forecastEntryForm    = ( SalesForecastEntryForm ) form;
        HttpSession session     = request.getSession();
        HashMap errors = new HashMap ();
        HashMap info = new HashMap ();
        User pUser = (User)session.getAttribute ( SessionKeys.USER_KEY );
        Calendar now = Calendar.getInstance();
        boolean currentMonthQtrReadOnly = false;
        int userType = SalesForecastEntryDAO.getForecastUserType( null, pUser );
        int monthTemp = -1;
        if ( userType == Constants.USER_TYPE_SALES_PERSON )
        {
            monthTemp = SalesForecastEntryDAO.getQuarterStartMonth( SalesForecastEntryDAO.getQuarterOfMonth( forecastEntryForm.getMonth() ) );
        }
        else
        {
            monthTemp = forecastEntryForm.getMonth();
        }
        if ( ! SalesForecastEntryDAO.isForecastEntryAllowed( monthTemp, forecastEntryForm.getYear() ) )
        {
            if ( userType == Constants.USER_TYPE_SALES_PERSON )
            {
                int selectedQtr = SalesForecastEntryDAO.getQuarterOfMonth( forecastEntryForm.getMonth() );
                int currentQtr = SalesForecastEntryDAO.getCurrenQuarter();
                if ( selectedQtr == currentQtr && forecastEntryForm.getYear() == now.get ( Calendar.YEAR ) )
                {
                    currentMonthQtrReadOnly = true;
                }
                else
                {
                    info.put ( INFO_FORECAST_ENTRY_TIME_ELAPSED, null );
                    request.setAttribute( SessionKeys.INFO_MESSAGES, info );
                    return mapping.findForward ( "saveSuccess" );
                }
            }
            else if ( forecastEntryForm.getMonth() == now.get ( Calendar.MONTH ) && forecastEntryForm.getYear() == now.get ( Calendar.YEAR ) ) //TO SHOW CURRENT MONTH DETAILS EVEN IF TIME ELAPSED
            {
                currentMonthQtrReadOnly = true;
            }
            else
            {
                info.put ( INFO_FORECAST_ENTRY_TIME_ELAPSED, null );
                request.setAttribute( SessionKeys.INFO_MESSAGES, info );
                return mapping.findForward ( "saveSuccess" );
            }
        }

        int spersonId = forecastEntryForm.getSpersonId();
        int userSpersonId   = -1;
        try
        {
            userSpersonId  = Integer.parseInt ( (String)session.getAttribute ( SessionKeys.USER_SALESPERSON_ID ) );
        }
        catch ( NumberFormatException e )
        {
              userSpersonId = -1;
        }

        int startMonth  = forecastEntryForm.getMonth();
        int startYear   = forecastEntryForm.getYear();
        int showNext    = forecastEntryForm.getShowNext();

        //step1:prepare month names to be displayed in the view
        ArrayList slotNames = SalesForecastEntryDAO.getSlotNames ( startMonth, startYear, showNext );
        request.setAttribute ( "slotNames", slotNames );
        ArrayList salesPersonIds = null;
        DecimalFormat decimalFormat = null;
        if(ConfigManager.getBooleanProperty(ConfigManager.FORECAST_SHOW_PRICE)) {
			decimalFormat = new DecimalFormat( "###########0.00" );
		} else {
			decimalFormat = new DecimalFormat( "###########0" );
		}
        if ( pUser.isActionAllowed( Functionality.FORECAST_ENTRY_FOR_ALL_SALES_PERSONS, User.USER_ACTION_MODIFY ) && spersonId == 0 ) //User is a Super User and selected all sales persons
        {
            salesPersonIds = SalesForecastEntryDAO.getAllSalesPersonIds( null );
        }
        else //USER DON'T HAVE THE PERMISSION FOR ALL SALES PERSONS SO SHOWING ONLY USER FORECAST DETAILS
        {
            if ( spersonId == 0 ) //User selected all salesPersons
            {
                AutoGrowingLinkedList rowDataList = SalesForecastEntryDAO.getRowDataList ( null, userSpersonId, startMonth, startYear, showNext, currentMonthQtrReadOnly, userType);
                if ( rowDataList != null && rowDataList.size() > 0 )
                {
                    RowData tempRowData = (RowData)rowDataList.get ( 0 );
                    AutoGrowingLinkedList slotDataList = tempRowData.getSlotDataList();
                    AutoGrowingLinkedList rowDataRunningTotal = new AutoGrowingLinkedList( NewLabelValueBean.class );
                    int slotDataListSize = ( slotDataList == null ? 0 : slotDataList.size() );
                    SlotData tempSlotData = null;
                    for ( int i =0; i < slotDataListSize; i++ )
                    {
                        tempSlotData = ( SlotData )slotDataList.get( i );
                        rowDataRunningTotal.add ( new NewLabelValueBean ( decimalFormat.format( tempSlotData.getRunningTotal() ), decimalFormat.format( tempSlotData.getRunningTotal() ) ) );
                    }
                    forecastEntryForm.setRowDataListRunningTotal( rowDataRunningTotal );
                }
                forecastEntryForm.setRowDataList( rowDataList );

                salesPersonIds    = SalesForecastEntryDAO.getSubOrdinateIds ( null, userSpersonId );
            }
            else
            {
                salesPersonIds = new ArrayList();
                salesPersonIds.add( Integer.toString( spersonId ) );
            }
        }
        int salesPersonIdsSize      =  ( salesPersonIds == null ) ? 0 : salesPersonIds.size();
        AutoGrowingLinkedList tempRowDataList   = null;
        ForecastData    forecastData            = null;
        AutoGrowingLinkedList forecastDataList  = new AutoGrowingLinkedList( ForecastData.class );
        int subOrdinateId   = -1;
        for ( int i = 0; i < salesPersonIdsSize; i++ )
        {
            try
            {
                subOrdinateId   = Integer.parseInt ( (String)salesPersonIds.get ( i ) );
                tempRowDataList = SalesForecastEntryDAO.getRowDataList ( null, subOrdinateId, startMonth, startYear, showNext, currentMonthQtrReadOnly, userType);
                String subOrdinateName  = null;
                if ( tempRowDataList != null && tempRowDataList.size() > 0 )
                {
                    RowData tempRowData = ( RowData ) tempRowDataList.get ( 0 );
                    AutoGrowingLinkedList slotDataList = tempRowData.getSlotDataList();
                    AutoGrowingLinkedList forecastDataRunningTotal = new AutoGrowingLinkedList( NewLabelValueBean.class );
                    int slotDataListSize = ( slotDataList == null ? 0 : slotDataList.size() );
                    SlotData tempSlotData = null;
                    for ( int k =0; k < slotDataListSize; k++ )
                    {
                        tempSlotData = ( SlotData )slotDataList.get( k );
                        forecastDataRunningTotal.add ( new NewLabelValueBean ( decimalFormat.format( tempSlotData.getRunningTotal() ), decimalFormat.format( tempSlotData.getRunningTotal() ) ) );
                    }
                    subOrdinateName     = tempRowData.getSalesPersonName();
                    forecastData    = new ForecastData();
                    forecastData.setSalesPersonId( subOrdinateId );
                    forecastData.setSalesPersonName( subOrdinateName );
                    forecastData.setRowDataList( tempRowDataList );
                    forecastData.setRunningTotal( forecastDataRunningTotal );
                    forecastData.setCollapsed ( ( salesPersonIdsSize == 1 ) ? false : true );
                    forecastDataList.add ( forecastData );
                }
            }
            catch ( Exception e )
            {
                subOrdinateId   = -1;
            }
        }
        forecastEntryForm.setForecastDataList( forecastDataList );
        return mapping.findForward( "salesForecastEntry" );
    }
}
